package com.example.demo2.controller;

import com.example.demo2.dao.UserDao;
import com.example.demo2.dao.impl.UserDaoImpl;
import com.example.demo2.model.User;
import com.example.demo2.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端页面获取用户数据
        String nameChecked = req.getParameter("username");
        String passChecked = req.getParameter("password");

        System.out.println(nameChecked);
        System.out.println(passChecked);

        //调用对应的业务层方法
        UserServiceImpl userService = new UserServiceImpl();
        User loginUser = userService.userLogin(nameChecked, passChecked);

        //根据方法执行的结果跳转
        if (loginUser != null){
            req.setAttribute("user",loginUser);
            req.getRequestDispatcher("index.jsp").forward(req,resp); // 跳转到首页
        }
        else{
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
